package images

import (
	"context"
	"server/internal/common/biz"
	"server/internal/svc"
	"server/internal/types"

	"github.com/docker/docker/api/types/filters"

	"github.com/docker/docker/api/types/registry"
	"github.com/zeromicro/go-zero/core/logx"
)

type SearchLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// search image
func NewSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchLogic {
	return &SearchLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SearchLogic) Search(req *types.SearchImageReq, respChan chan []types.SearchImageResp,
	errChan chan *biz.Error) {
	defer close(respChan)
	result, err := l.svcCtx.DockerCli.ImageSearch(context.TODO(), req.RepoTag, registry.SearchOptions{
		Limit: 100,
		Filters: func() filters.Args {
			if req.IsOfficial {
				return filters.NewArgs(filters.Arg("is-official", "true"))
			}
			return filters.NewArgs()
		}(),
	})
	if err != nil {
		l.Logger.Error("search image error: ", err)
		errChan <- biz.ImageSearchError
		return
	}
	if result == nil && len(result) == 0 {
		l.Logger.Error("search image not found")
		errChan <- biz.ImageSearchNotFoundError
		return
	}

	resp := make([]types.SearchImageResp, 0, len(result))
	for _, item := range result {
		resp = append(resp, types.SearchImageResp{
			StarCount:   item.StarCount,
			IsOfficial:  item.IsOfficial,
			Name:        item.Name,
			Description: item.Description,
		})
	}
	respChan <- resp
}
